import sys
sys.path.insert(0, '/home/yjj/xquant/')
sys.path.insert(0, '/opt/xquant/')

import time
import pandas as pd
import oandapyV20
import oandapyV20.endpoints.instruments as instruments
from event import BarEvent


class BarPrices(object):
    def __init__(self, domain, access_token, account_id,
                instruments, granularity, events_queue,
                asset = 'currency'):
        self.asset=asset
        self.domain = domain
        self.access_token = access_token
        self.account_id = account_id
        self.instruments = instruments
        self.granularity = granularity
        self.events_queue = events_queue
        self.client = oandapyV20.API(access_token = self.access_token)
        self.transform_timeframe_to_second_num = {
                                                'S5':5,
                                                'S10':10,
                                                'S15':15,
                                                'S30':30,
                                                'M1':60,
                                                'M2':120,
                                                'M3':180,
                                                'M4':240,
                                                'M5':300,
                                                'M10':600,
                                                'M15':900,
                                                'M30':1800,
                                                'H1':3600,
                                                'H2':7200,
                                                'H3':10800,
                                                'H4':14400,
                                                'H8':28800
                                            }



    def get_candles(self, start_date, end_date,
                    price = 'M', instrument = "EUR_USD",
                    granularity = "M30"):
        #获取oanda的数据
        params = {
                        "from": start_date,
                        'to':end_date,
                        'price':price,
                        "granularity": granularity
                        }
        r = instruments.InstrumentsCandles(instrument = instrument, params = params)
        data = self.client.request(r)
        return data



    def get_add_candle(self):
        '''根据本机测试，每次跑一次这个判断函数需要的时间大约为3.45 µs，时间非常小
        3.45 µs ± 11.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

        Returns:
            [Boolean] -- [返回正确与否]
        '''

        local_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        con = False
        if self.granularity == 'M1':
            if local_time[-2:] == '00':
                return True
        if self.granularity == 'M5':
            if local_time[-4:] == '5:00' or local_time[-4:] == '0:00':
                return True
        if self.granularity == 'M15':
            if local_time[-5:] == '15:00' or local_time[-5:] == '00:00' or \
                local_time[-5:] == '30:00' or local_time[-5:] == '45:00':
                return True
        if self.granularity == 'M30':
            if local_time[-4:] == '00:00' or local_time[-5:] == '30:00' :
                return True
        if self.granularity == 'H1':
            if local_time[-4:] == '00:00':
                return True
        return con


    def _to_queue(self):
        while True:
            '''每0.1秒判断一次，是否需要pull一下Ｋ线数据，如果需要，就下载，加入进程
            '''
            if self.get_add_candle():
                num = 28800
                num_add_granularity = num+self.transform_timeframe_to_second_num[self.granularity]
                now_time = time.strftime('%Y-%m-%dT%H:%M:%S.000000000Z', time.localtime(time.time()-num))
                pre_now_time = time.strftime('%Y-%m-%dT%H:%M:%S.000000000Z', time.localtime(time.time()-num_add_granularity))
                now_time = now_time[:17]+'00'+now_time[19:]
                pre_now_time = pre_now_time[:17]+'00'+pre_now_time[19:]
                data = self.get_candles(pre_now_time, now_time, price = 'M',
                            instrument = self.instruments, granularity = self.granularity)
                if len(data['candles']) > 0:
                    self.instrument = data['instrument']
                    self.time = data['candles'][0]['time']
                    self.open = data['candles'][0]['mid']['o']
                    self.high = data['candles'][0]['mid']['h']
                    self.low =  data['candles'][0]['mid']['l']
                    self.close = data['candles'][0]['mid']['c']
                    self.vol = data['candles'][0]['volume']
                    tev = BarEvent(self.asset,self.instrument, self.time, self.open,
                                    self.high, self.low, self.close, self.vol)
                    self.events_queue.put(tev)
            time.sleep(0.1)